home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8270 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  64 lines

  1. Path: news1.interserv.net!news
  2. From: <dvisage@interserv.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Convert string to char*
  5. Date: 16 Feb 1996 11:08:42 GMT
  6. Organization: InterServ News Service
  7. Message-ID: <4g1ojq$r4r@lal.interserv.net>
  8. NNTP-Posting-Host: dd76-132.compuserve.com
  9. Content-Type: text/plain
  10. Content-length: 1463
  11. X-Newsreader: AIR Mosaic (32-bit) 4.00
  12.  
  13.  
  14. >something like:
  15. >
  16. >    char* operator ?? ()
  17. >
  18. >so that my string class can also return char*. Please help. Thanks,
  19. >
  20. >Abu Wawda
  21. >wawda@scf.usc.edu
  22. >
  23.  
  24. class YourStringClass
  25. {
  26.      char* _data;    //  Points to string data
  27.  
  28. public :
  29.  
  30.    operator char* () { return _data; }
  31. };
  32.  
  33.  
  34. There are several problems here :
  35.  
  36. (1) Why in the world would you create your string class when eveyone and
  37.      their mother (except mine) has already written one?  In fact, there is
  38.      already an ANSI standard C++ string class.  It is derived from a template
  39.      call basic_string<>.  I won't go all the gory details, but I am sure that it
  40.      will suit most of your needs.  You should be able to get a copy of 
  41.      bstring.h by downloading the most recent version of STL.
  42.  
  43. (2) User defined conversions are inherently dangerous
  44.   
  45.      For example, assume the following code :
  46.  
  47.      YourStringClass str;
  48.  
  49.      cout << str << endl;
  50.  
  51.     Unless you make sure to define :
  52.  
  53.     ostream& operator<<(ostream& os, const YourStringClass& str);
  54.  
  55.     The compiler will automatically call your operator char* () function
  56.     and then will call ostream::operator<<(char *).
  57.  
  58.     If this is not what you want, you are SOL.
  59.  
  60.     P.S - This is the reason that the ANSI string class requires you to call
  61.              the member function data() to get the chararacter string pointer
  62.              of a string data type.  It used to be called c_str().
  63.  
  64.